package com.onepower.admin.controller;


import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.onepower.core.domain.request.CreateMatchScheduleForm;
import com.onepower.core.domain.request.MatchScheduleQuery;
import com.onepower.core.domain.response.MatchScheduleInfo;
import com.onepower.core.domain.response.MatchScoreInfo;
import com.onepower.core.modules.repository.entity.MatchReferee;
import com.onepower.core.modules.repository.entity.MatchSchedule;
import com.onepower.core.modules.repository.entity.MatchScheduleLocked;
import com.onepower.core.modules.repository.entity.MatchScheduleLogicSocre;
import com.onepower.core.modules.service.*;
import com.onepower.core.result.BizResultCode;
import com.onepower.core.result.CommonResult;
import com.onepower.core.utils.DateUtils;
import com.onepower.core.utils.ResultUtils;
import com.onepower.core.utils.SecurityUtils;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.io.Serializable;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 比赛场次表 前端控制器
 * </p>
 *
 * @author kin
 * @since 2018-08-06
 */
@RestController
@RequestMapping("api/match/schedule")
public class MatchScheduleController {

    @Autowired
    private IMatchScheduleService matchScheduleService;

    @Autowired
    private IMatchScoreService matchScoreService;

    @Autowired
    private IMatchRefereeService matchRefereeService;

    @Autowired
    private IMatchScheduleLogicScoreService matchScheduleLogicScoreService;

    @Autowired
    private IMatchScheduleLockedService matchScheduleLockedService;

    @Autowired
    HttpServletRequest request;

    @PostMapping("import")
    public CommonResult importSchedule(@RequestParam("matchId") Integer matchId,
                                       @RequestParam("file") MultipartFile file) throws Exception {

        return matchScheduleService.createScheduleByImport(matchId, file);
    }

    @RequestMapping(value = "createScheduleByOnline", method = RequestMethod.POST)
    public CommonResult createScheduleByOnline(@RequestBody List<CreateMatchScheduleForm> forms) throws IOException {
        return matchScheduleService.createScheduleServiceByOnline(forms);
    }

    @RequestMapping(value = "info", method = RequestMethod.GET)
    public CommonResult getSchedule(@RequestParam(value = "matchScheduleId", required = false, defaultValue = "-1") int matchScheduleId,
                                    @RequestParam(value = "type", required = false, defaultValue = "-1") int type
                                    ) {
        if (type != -1) {
            MatchScheduleInfo schedule = matchScheduleService.getSchedule(matchScheduleId);
            try {
                MatchSchedule matchSchedule = matchScheduleService.getMatchSchedule(schedule.getScoreString().replace("score.asp","tkd.asp"), schedule.getType());
                matchSchedule.setId(matchScheduleId);
                matchSchedule.setLockTwoTime(schedule.getLockTwoTime());
                matchSchedule.setIsComplete(schedule.getIsComplete());
                matchSchedule.setType(schedule.getType());
                matchSchedule.setTwoTime(schedule.getTwoTime());
                matchScheduleService.updateById(matchSchedule);
            }catch (Exception e){
                e.printStackTrace();
            }
        }
        MatchScheduleInfo schedule = matchScheduleService.getSchedule(matchScheduleId);
        //选手姓名只取11个字符
        if(StringUtils.isNotBlank(schedule.getBluePlayer()) && schedule.getBluePlayer().length() > 11){
        	schedule.setBluePlayer(schedule.getBluePlayer().substring(0, 11));
        }
        if(StringUtils.isNotBlank(schedule.getRedPlayer()) && schedule.getRedPlayer().length() > 11){
        	schedule.setRedPlayer(schedule.getRedPlayer().substring(0, 11));
        }
        return ResultUtils.ok(schedule);
    }

    @RequestMapping(value = "list", method = RequestMethod.GET)
    public CommonResult list(@RequestParam(value = "matchId", required = false, defaultValue = "-1") int matchId,
                             @RequestParam(value = "matchPlaceId", required = false, defaultValue = "-1") int matchPlaceId,
                             @RequestParam(value = "scheduleLevel", required = false, defaultValue = "") String scheduleLevel,
                             @RequestParam(value = "scheduleGroup", required = false, defaultValue = "") String scheduleGroup,
                             @RequestParam(value = "scheduleName", required = false, defaultValue = "") String scheduleName,
                             @RequestParam(value = "state", required = false, defaultValue = "-1") int state,
                             @RequestParam(value = "pageNum", required = false, defaultValue = "1") int pageNum,
                             @RequestParam(value = "pageSize", required = false, defaultValue = "20") int pageSize) {
        MatchScheduleQuery query = new MatchScheduleQuery();
        query.setMatchId(matchId);
        query.setMatchPlaceId(matchPlaceId);
        query.setScheduleLevel(scheduleLevel);
        query.setScheduleGroup(scheduleGroup);
        query.setScheduleName(scheduleName);
        query.setState(state);
        Page<MatchScheduleInfo> scheduleList = matchScheduleService.getScheduleList(new Page<>(pageNum, pageSize), query);

        for (MatchScheduleInfo matchScheduleInfo : scheduleList.getRecords()){
            int type = matchScheduleInfo.getType();
            if (type == 1 && !matchScheduleInfo.getTwoTime()){
                MatchScheduleLogicSocre msls  = matchScheduleLogicScoreService.scheduleLogicScore(matchScheduleInfo.getId(),1);
                Double A = Double.valueOf(0);
                Double P = Double.valueOf(0);
                Double T = Double.valueOf(0);
                if (msls != null){
                    T = T + msls.getTotalScore();
                    A = A + msls.getAccuracyScore();
                    P = P +  msls.getExpressivenessScore();
                    matchScheduleInfo.setAccuracyScore(A);
                    matchScheduleInfo.setExpressivenessScore(P);
                    matchScheduleInfo.setTotalScore(T );
                }
            }else if (type == 1 && matchScheduleInfo.getTwoTime()){
                MatchScheduleLogicSocre ms1 = matchScheduleLogicScoreService.scheduleLogicScore(matchScheduleInfo.getId(),1);
                MatchScheduleLogicSocre ms2 = matchScheduleLogicScoreService.scheduleLogicScore(matchScheduleInfo.getId(),2);
                if (ms1 != null && ms2 != null){
                    Double T1 = Double.valueOf(0);
                    Double T2 = Double.valueOf(0);
                    Double T3 = Double.valueOf(0);
                    Map<String,Object> map = new HashMap<>();
                    T1 = (ms1.getAccuracyScore() + ms2.getAccuracyScore())/2;
                    T2 = (ms1.getExpressivenessScore() + ms2.getExpressivenessScore())/2;
                    T3 = (ms1.getTotalScore() + ms2.getTotalScore())/2;
                    matchScheduleInfo.setAccuracyScore(T1);
                    matchScheduleInfo.setExpressivenessScore(T2);
                    matchScheduleInfo.setTotalScore(T3);
                }
            }else if (type == 1 && matchScheduleInfo.getTwoTime()){
                MatchScheduleLogicSocre ms1 = matchScheduleLogicScoreService.scheduleLogicScore(matchScheduleInfo.getId(),1);
                MatchScheduleLogicSocre ms2 = matchScheduleLogicScoreService.scheduleLogicScore(matchScheduleInfo.getId(),2);
                if (ms1 != null && ms2 != null){
                    Double T1 = Double.valueOf(0);
                    Double T2 = Double.valueOf(0);
                    Double T3 = Double.valueOf(0);
                    Map<String,Object> map = new HashMap<>();
                    T1 = (ms1.getAccuracyScore() + ms2.getAccuracyScore())/2;
                    T2 = (ms1.getExpressivenessScore() + ms2.getExpressivenessScore())/2;
                    T3 = (ms1.getTotalScore() + ms2.getTotalScore())/2;
                    matchScheduleInfo.setAccuracyScore(T1);
                    matchScheduleInfo.setExpressivenessScore(T2);
                    matchScheduleInfo.setTotalScore(T3);
                }
                return ResultUtils.ok();


            }/*else if (matchScheduleInfo.getType() == 2 && matchScheduleInfo.getTwoTime()){
                MatchScheduleLogicSocre ms1 = matchScheduleLogicScoreService.scheduleLogicScore(matchScheduleInfo.getId(),1);
                MatchScheduleLogicSocre ms3 = matchScheduleLogicScoreService.scheduleLogicScore(matchScheduleInfo.getId(),3);
                MatchScheduleLogicSocre ms2 = matchScheduleLogicScoreService.scheduleLogicScore(matchScheduleInfo.getId(),2);
                MatchScheduleLogicSocre ms4 = matchScheduleLogicScoreService.scheduleLogicScore(matchScheduleInfo.getId(),4);
                if (ms1 != null && ms2 != null && ms3 != null && ms4 != null){
                    Double T1 = Double.valueOf(0);  //青
                    Double T2 = Double.valueOf(0);  //红
                    Map<String,Object> map = new HashMap<>();
                    T1 = (ms1.getTotalScore() + ms3.getTotalScore())/2;
                    T2 = (ms2.getTotalScore() + ms4.getTotalScore())/2;

                }
            }*/

        }

        return ResultUtils.ok(scheduleList);
    }

    @RequestMapping(value = "deleteSchedule", method = RequestMethod.POST)
    public CommonResult deleteSchedule(@RequestBody Integer[] scheduleIds){
        for (Integer id : scheduleIds){
            matchScheduleService.removeById(id);
        }
        return ResultUtils.ok();
    }


    @RequestMapping(value = "getMatchScoreList", method = RequestMethod.GET)
    public CommonResult getMatchScoreList(
            @RequestParam(value = "matchScheduleId", required = false, defaultValue = "-1") int matchScheduleId,
            @RequestParam(value = "scoreType", required = false,defaultValue = "-1") int scoreType
    ) {
        if (scoreType == -1){
            MatchScheduleInfo matchScheduleInfo = matchScheduleService.getSchedule(matchScheduleId);
            scoreType = matchScheduleInfo.getLockTwoTime();
        }
        List<Map<String,Object>> matchScoreInfoList = matchScoreService.getMatchScoreList(matchScheduleId,scoreType);
        return ResultUtils.ok(matchScoreInfoList);
    }

    @RequestMapping(value = "getRefereeScoreList", method = RequestMethod.GET)
    public CommonResult getRefereeScoreList(
            @RequestParam(value = "matchScheduleId", required = true) int matchScheduleId,
            @RequestParam(value = "matchId", required = true) int matchId,
            @RequestParam(value = "matchAdminId", required = true) int matchAdminId,
            @RequestParam(value = "scoreType", required = true) int scoreType
            ){
        MatchScheduleInfo matchScheduleInfo = matchScheduleService.getSchedule(matchScheduleId);
        List<Map<String,Object>> matchScoreInfoList = matchScoreService.selectRefereeScoreList(matchId,matchAdminId,matchScheduleId,matchScheduleInfo.getLockTwoTime());
        for (Map<String,Object> map : matchScoreInfoList) {
            if (map.get("expressiveness") == null) {
                map.put("expressiveness",null);
            }
            if (map.get("accuracy") == null) {
                map.put("accuracy",null);
            }
            if (map.get("winner") == null) {
                map.put("winner",null);
            }
        }
        return ResultUtils.ok(matchScoreInfoList);
    }

    @RequestMapping(value = "getLockMatch", method = RequestMethod.GET)
    public CommonResult getLockMatch(@RequestParam int matchId,
                                     @RequestParam int matchAdminId) {
        MatchScheduleInfo matchScheduleInfo = matchScheduleService.getMatchScheduleLockedByReferee(matchId, matchAdminId);
        return ResultUtils.ok(matchScheduleInfo);
    }


    @RequestMapping(value = "updateTeamAndName", method = RequestMethod.POST)
    public CommonResult updateTeamAndName(@RequestBody MatchScheduleInfo matchScheduleInfo) {
        Map map = new HashMap();
        map.put("matchScheduleId", matchScheduleInfo.getId());
        map.put("blueTeam", matchScheduleInfo.getBlueTeam());
        map.put("bluePlayer", matchScheduleInfo.getBluePlayer());
        map.put("redTeam", matchScheduleInfo.getRedTeam());
        map.put("redPlayer", matchScheduleInfo.getRedPlayer());
        return matchScheduleService.updateMatchSchedule(map);
    }

    @RequestMapping(value = "updateScore", method = RequestMethod.POST)
    public CommonResult updateScore(@RequestBody MatchScheduleInfo matchScheduleInfo) {
        Map map = new HashMap();
        map.put("matchScheduleId", matchScheduleInfo.getId());
        map.put("expressivenessScore", matchScheduleInfo.getExpressivenessScore());
        map.put("accuracyScore", matchScheduleInfo.getAccuracyScore());
        map.put("totalScore", matchScheduleInfo.getTotalScore());
        return matchScheduleService.updateMatchSchedule(map);
    }

    @RequestMapping(value = "updatePsEntry", method = RequestMethod.GET)
    public CommonResult updatePsEntry(@RequestParam(value = "psEntry") String psEntry, int matchScheduleId) {
        Map map = new HashMap();
        map.put("matchScheduleId", matchScheduleId);
        map.put("psEntry", psEntry);
        return matchScheduleService.updateMatchSchedule(map);
    }

    @RequestMapping(value = "updateMatchSchedule", method = RequestMethod.POST)
    public CommonResult updateMatchSchedule(@RequestParam(value = "id") int id,
                                            @RequestParam(value = "matchStatus1") String matchStatus1,
                                            @RequestParam(value = "matchStatus2") String matchStatus2,
                                            @RequestParam(value = "blueTeam") String blueTeam,
                                            @RequestParam(value = "bluePlayer") String bluePlayer,
                                            @RequestParam(value = "redTeam" ,defaultValue = "") String redTeam,
                                            @RequestParam(value = "redPlayer",defaultValue = "") String redPlayer
                                            ){
        MatchScheduleInfo matchScheduleInfo = matchScheduleService.getSchedule(id);
        MatchSchedule matchSchedule = new MatchSchedule();
        matchSchedule.setId(id);
        matchSchedule.setBlueTeam(blueTeam);
        matchSchedule.setBluePlayer(bluePlayer);
        matchSchedule.setRedPlayer(redPlayer);
        matchSchedule.setRedTeam(redTeam);
        matchSchedule.setMatchStatus1(matchStatus1);
        matchSchedule.setMatchStatus2(matchStatus2);
        matchSchedule.setLockTwoTime(matchScheduleInfo.getLockTwoTime());
        matchSchedule.setTwoTime(matchScheduleInfo.getTwoTime());
        matchScheduleService.saveOrUpdate(matchSchedule);
        return ResultUtils.ok();
    }

    @RequestMapping(value = "showScore", method = RequestMethod.GET)
    public CommonResult showScore(@RequestParam(value = "matchScheduleId") int matchScheduleId) {
        Map map = new HashMap();
        map.put("matchScheduleId", matchScheduleId);
        map.put("isShowScore", "");
        return matchScheduleService.updateMatchSchedule(map);
    }

    @RequestMapping(value = "showRanking", method = RequestMethod.GET)
    public CommonResult showRanking(@RequestParam(value = "matchScheduleId") int matchScheduleId) {
        Map map = new HashMap();
        map.put("matchScheduleId", matchScheduleId);
        map.put("isShowRanking", "");
        return matchScheduleService.updateMatchSchedule(map);
    }

    @ResponseBody
    @RequestMapping(value = "checkReferee", method = RequestMethod.GET)
    public CommonResult checkReferee(@RequestParam int refereeId) {
        MatchReferee matchReferee = matchRefereeService.getById(refereeId);
        Long diffMin = DateUtils.sub2Min(matchReferee.getCheckTime(),new Date());
        return diffMin > 1 ? ResultUtils.error(BizResultCode.REFEREE_DISCONNECT) : ResultUtils.ok();
    }

    @RequestMapping(value = "matchScheduleForCodeList", method = RequestMethod.GET)
    public CommonResult matchScheduleForCodeList(@RequestParam(value = "matchId", required = false, defaultValue = "-1") int matchId,
            									 @RequestParam(value = "matchPlaceId", required = false, defaultValue = "-1") int matchPlaceId){
    	if(matchPlaceId == -1){
    		List<Map<String,Object>> list = matchScheduleService.matchScheduleForCodeList();
            return ResultUtils.ok(list);
    	}
    	List<Map<String,Object>> list = matchScheduleService.getMatchScheduleCodeByMatchPlace(matchId, matchPlaceId);
        return ResultUtils.ok(list);
    }

    @RequestMapping(value = "lockTwoTimeChange", method = RequestMethod.POST)
    public CommonResult lockTwoTimeChange(@RequestParam(value = "matchScheduleId") int matchScheduleId,
                                          @RequestParam(value = "lockTwoTime") int lockTwoTime
                                          ) {
        Integer currentUserId = SecurityUtils.getCurrentUserId(request);
        MatchScheduleInfo matchScheduleInfo = matchScheduleService.getSchedule(matchScheduleId);
        MatchScheduleLocked matchScheduleLocked = matchScheduleLockedService.querySchedleLockSchedule(currentUserId,matchScheduleInfo.getMatchId(),matchScheduleId);
        if (matchScheduleLocked != null) {
            MatchSchedule matchSchedule = new MatchSchedule();
            matchSchedule.setId(matchScheduleId);
            matchSchedule.setLockTwoTime(lockTwoTime);
            matchSchedule.setTwoTime(matchScheduleInfo.getTwoTime());
            boolean b = matchScheduleService.updateById(matchSchedule);
            return ResultUtils.ok(b);
        } else {
            return ResultUtils.error(600,"不能切换");
        }
    }

}
